<template>
    <div class="search-box">
        <el-select v-model="currentLake.label" filterable placeholder="Select" style="width: 240px"
            :filter-method="customFilter" @change="handleChange">
            <el-option v-for="item in filteredLakes" :key="item.value" :label="item.label" :value="item" />
        </el-select>
    </div>
    <div id="container"></div>
    <div id="panel"></div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, ref } from 'vue';
import AMapLoader from "@amap/amap-jsapi-loader";
let map = null;
let infoWindow = null;
let geolocation = null;
let locationInfo = null
let driving = null;
let Amap2 = null
let lakes = require("../../public/lakes.json")
let lakesOption = ref(lakes.map(lake => {
    return {
        value: lake.path[0],
        label: lake.name,
        fish: lake.fish
    }
}))
let filteredLakes = ref([...lakesOption.value])
let currentLake = ref({
    value: [],
    label: "",
    fish: []
})
// 自定义筛选方法 鳙鱼
const customFilter = (value) => {
    if (!value) {
        filteredLakes.value = [...lakesOption.value]
    } else {
        const lowerCaseValue = value.toLowerCase()
        filteredLakes.value = lakesOption.value.filter(item => {
            return (
                item.label.toLowerCase().includes(lowerCaseValue) ||
                item.fish.some(f => f.toLowerCase().includes(lowerCaseValue))
            )
        })
    }
};
const handleChange = (value) => {
    console.log(value)
    daohang(value?.value[0], value?.value[1])
}
onMounted(() => {
    window._AMapSecurityConfig = {
        securityJsCode: "f2c6cb031e7c35eca926eab8ec57a958",
    };
    AMapLoader.load({
        key: "b704bd3f11f84a00314fd1e71babc37b",
        // version: "2.0",
        plugins: [
            'AMap.Scale',
            'AMap.Marker',
            "AMap.InfoWindow",//地图弹窗
            "AMap.PlaceSearch",//地点搜索
            "AMap.Geolocation",//定位到当前位置
            "AMap.Geocoder",//经纬度进行逆地理编码查询
            "AMap.Driving",//驾车导航
            "AMap.Transfer",//公交导航
            "AMap.Walking",//步行导航
            "AMap.Riding",//骑行导航
        ]
    })
        .then((AMap) => {
            map = new AMap.Map("container", {
                resizeEnable: true,
                viewMode: "3D",
                zoom: 12,
                // center: [114.3054, 30.5928], // 武汉中心坐标
                center: [114.356769, 30.474852],// 华中农业大学坐标
            });
            map.addControl(new AMap.Scale());
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                timeout: 10000, // 设置定位超时时间，默认：无穷大
                // offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                position: 'RB', //  定位按钮的排放位置,  RB表示右下
            })
            map.addControl(geolocation);
            geolocation.getCurrentPosition((status, result) => {
                if (status == 'complete') {
                    const { position } = result
                    locationInfo = [position['R'], position['Q']]
                    console.log(locationInfo)
                } else {
                    console.log(result);
                }
            })
            driving = new AMap.Driving({
                map: map,
                panel: "panel"
            });
            map.addControl(driving);

            Amap2 = AMap
            initInfoWindow(Amap2);
            addLakes(Amap2);
            addMapControls(Amap2);
        })
        .catch((e) => {
            console.log(e);
        });
});

const initInfoWindow = (AMap) => {
    infoWindow = new AMap.InfoWindow({
        offset: new AMap.Pixel(0, -30),
        // autoMove: true,
        // closeWhenClickMap: true
    });
};

const addLakes = (AMap) => {
    lakes.forEach((lake) => {
        // 添加湖泊名称标注
        const mark = new AMap.Marker({
            icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            position: lake.path,
            offset: new AMap.Pixel(0, 0)
        })
        mark.on('click', (e) => showLakeInfo(lake, e.lnglat));
        mark.setMap(map);
    });
};

const showLakeInfo = (lake, position) => {
    daohang(lake.path[0][0], lake.path[0][1])
    const content = `
            <div class="info-window">
              <p>名称：${lake.name}</p>
              <p>位置 ${lake.location}</p>
              <p>面积：${lake.area}</p>
              <p>历史：${lake.content}</p>
              <p>鱼群：${lake.fish.join(",")}</p>
            </div>
          `;
    infoWindow.setContent(content);
    infoWindow.open(map, position);
};
const daohang = (a, b) => {
    // driving.search(new Amap2.LngLat(locationInfo[0], locationInfo[1]), new Amap2.LngLat(a, b), function (status, result) {
    driving.search(new Amap2.LngLat(114.356769, 30.474852), new Amap2.LngLat(a, b), function (status, result) {
        if (status === 'complete') {
            console.log('路线规划成功');
        } else {
            console.log('路线规划失败：' + result.info);
        }
    });
}
// 添加地图控件
const addMapControls = (AMap) => {
    map.addControl(new AMap.Scale());
};
onBeforeUnmount(() => {
    if (map) {
        map.destroy();
    }
});

</script>

<style scoped>
.search-box {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    gap: 10px;
    margin-bottom: 20px;
}

#container {
    width: 100%;
    height: 800px;
}

#panel {
    position: fixed;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 55px;
    right: 10px;
    width: 280px;
}

#panel .amap-call {
    background-color: #009cf9;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
}

#panel .amap-lib-driving {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow: hidden;
}

.info {
    width: 26rem;
}

.lake-label {
    background-color: rgba(255, 255, 255, 0.8);
    padding: 2px 5px;
    border-radius: 3px;
    font-size: 12px;
}

.info-window {
    background-color: white;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
</style>